package com.winai.launcher.base.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.Date;

public class DB_Common {
    //通用key value 存储
    //数据库文件默认路径 data/data/<`package_name>/database/

    public static final String TABLE_NAME="common_caches";//表名
    private static StringBuilder ss=DBDef.startKeyDef(TABLE_NAME);

    private static final String KEY_KEYS=DBDef.keyDef(ss,"keys",DBDef.varchar(65));//key
    private static final String KEY_DATES=DBDef.keyDef(ss,"date",DBDef.bigint());//key
    private static final String KEY_VALUES=DBDef.keyDef(ss,"keyset",DBDef.text());//values

    private static final String CREATE_STRING =DBDef.endKeyDef(ss);


    private DBHelper mDBHelper;
    public DB_Common(Context context){
        mDBHelper=new DBHelper(context,CREATE_STRING);
    }

    public DBHelper getDbHelper() {
        return mDBHelper;
    }

    //增加一条信息
    public boolean add(String key,String value){
        if(key==null || value==null) return false;
        del(key);//每个用户只能保存一条
        SQLiteDatabase db=mDBHelper.getWritableDatabase();
        ContentValues values=new ContentValues();

        long longDate=new Date().getTime();//当前时间

        values.put(KEY_KEYS,key);
        values.put(KEY_DATES,longDate);
        values.put(KEY_VALUES,value);

        long id=db.insert(TABLE_NAME,null,values);
        db.close();

        return id!=0;
    }

    //删除一条记录
    public void del(String  key){
        if(key!=null) {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            db.delete(TABLE_NAME, KEY_KEYS + "=?", new String[]{key});
            db.close();
        }
    }

    //查询一条记录
    public String get(String key){
        SQLiteDatabase db=mDBHelper.getReadableDatabase();

        String selectQuery="SELECT * FROM " + TABLE_NAME  + " WHERE " +  KEY_KEYS + "=?";
        String rcd=null;
        Cursor cursor=db.rawQuery(selectQuery,new String[]{key});
        if(cursor.moveToFirst()){
            do{
                rcd=make(cursor);
                if(rcd!=null) break;
            }while(cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return rcd;
    }

    //根据查询结果获得Record
    private String make(Cursor cursor){
        return cursor.getString(cursor.getColumnIndex(KEY_VALUES));
    }

}
